package api

import (
	"encoding/json"
	"io"
	"net/http"

	"github.com/jmoiron/sqlx"
)

// hello 接口
func HandlerUser(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Hello World\n"))
}

// 帮助信息接口
func HandlerHelp(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("httptest 接口文档\n"))
	w.Write([]byte("1. 帮助接口: 请求 / \n"))
	w.Write([]byte("2. hello 接口: 请求 /hello \n"))
}

type API struct {
	DB *sqlx.DB
}

// DecodeFromStream 从 io.Reader 中解码数据到指定的结构体
func (a *API) DecodeFromStream(r io.Reader, v interface{}) error {
	return json.NewDecoder(r).Decode(v)
}

// EncodeToStream 将数据编码并写入 io.Writer
func (a *API) EncodeToStream(w io.Writer, v interface{}) error {
	return json.NewEncoder(w).Encode(v)
}

// 用户注册接口
func (a *API) HandlerRegister(w http.ResponseWriter, r *http.Request) {
	// 1. 检查请求方法
	if r.Method != http.MethodPost {
		http.Error(w, "只支持POST方法", http.StatusMethodNotAllowed)
		return
	}

	// 2. 解析JSON请求体
	var req struct {
		Username string `json:"username"`
		Password string `json:"password"`
	}

	if err := a.DecodeFromStream(r.Body, &req); err != nil {
		http.Error(w, "无效的JSON格式", http.StatusBadRequest)
		return
	}

	// 3. 验证必填字段
	if req.Username == "" || req.Password == "" {
		http.Error(w, "用户名和密码不能为空", http.StatusBadRequest)
		return
	}

	// 4. 检查用户名是否已存在
	var count int
	err := a.DB.Get(&count, "SELECT COUNT(*) FROM users WHERE username = ?", req.Username)
	if err != nil {
		http.Error(w, "数据库查询错误", http.StatusInternalServerError)
		return
	}

	if count > 0 {
		http.Error(w, "用户名已存在", http.StatusConflict)
		return
	}

	// 5. 插入新用户（实际应用中密码应该加密）
	if _, err = a.DB.Exec("INSERT INTO users (username, password) VALUES (?, ?)", req.Username, req.Password); err != nil {
		http.Error(w, "用户注册失败", http.StatusInternalServerError)
		return
	}

	// 6. 返回成功响应
	w.WriteHeader(http.StatusCreated)
	w.Write([]byte("用户注册成功"))
}
